import requests
import json
import pandas as pd
import os
from requests.adapters import HTTPAdapter
import uuid
# https://www.cnblogs.com/Security-Darren/p/4192566.html#m7

uid = 'f4460918f2b3296ab11e36ff'
bmap_boundary_url = 'https://map.baidu.com/?newmap=1&reqflag=pcmap&biz=1&from=webmap&da_par=direct&pcevaname=pc4.1&qt=ext&uid=' + uid + '&c=340&ext_ver=new&tn=B_NORMAL_MAP&nn=0&auth=fw9wVDQUyKS7%3DQ5eWeb5A21KZOG0NadNuxHNBxBBLBHtxjhNwzWWvy1uVt1GgvPUDZYOYIZuEt2gz4yYxGccZcuVtPWv3GuxNt%3DkVJ0IUvhgMZSguxzBEHLNRTVtlEeLZNz1%40Db17dDFC8zv7u%40ZPuxtfvSulnDjnCENTHEHH%40NXBvzXX3M%40J2mmiJ4Y&ie=utf-8&l=19&b=(12679382.095,2565580.38;12679884.095,2565907.38)&t=1573133634785'

s = requests.Session()
s.mount('http://', HTTPAdapter(max_retries=3))
s.mount('https://', HTTPAdapter(max_retries=3))

data = s.get(url=bmap_boundary_url, timeout=5, headers={"Connection": "close"})
data = data.text
print(data)
data = json.loads(data)
print(data)
content = data['current_city']
if not 'geo' in content:
    print('asd')
geo = content['geo']
i = 0
strsss = ''
for jj in str(geo).split('|')[2].split('-')[1].split(','):
    jj = str(jj).strip(';')
    if i % 2 == 0:
        strsss = strsss + str(jj) + ','
    else:
        strsss = strsss + str(jj) + ';'
    i = i + 1
strsss.strip(";")



def transform_coordinate_batch(coordinates):
    req_url = 'http://api.map.baidu.com/geoconv/v1/?coords='+coordinates+'&from=6&to=5&ak=' + bmap_key

    s = requests.Session()
    s.mount('http://', HTTPAdapter(max_retries=3))
    s.mount('https://', HTTPAdapter(max_retries=3))

    data = s.get(req_url, timeout=5, headers={"Connection": "close"})  # , proxies=proxies
    data = data.text
    data = json.loads(data)
    coords = ''
    if data['status'] == 0:
        result = data['result']
        if len(result) > 0:
            for res in result:
                lng = res['x']
                lat = res['y']
                coords = coords + ";" + str(lng) + "," + str(lat)
    return coords.strip(";")


file_name = 'data/boundary_result_wgs84 - polygon.csv'
csv_file = pd.read_csv(file_name, encoding='gbk')

a_col = []
data_csv = {}
numbers, xs, ys, uids = [], [], [], []
index = 1
for i in range(len(csv_file)):
    boundary = str(csv_file['boundary'][i])
    uid = str(uuid.uuid4()).replace('-', '')

    if boundary is not '':
        for point in boundary.split(";"):
            lng = point.split(",")[0]
            lat = point.split(",")[1]
            xs.append(lng)
            ys.append(lat)
            numbers.append(index)
            uids.append(uid)

            index = index + 1
data_csv['number'] = numbers
data_csv['x'] = xs
data_csv['y'] = ys
data_csv['uid'] = uids

df = pd.DataFrame(data_csv)
df.to_csv(os.getcwd() + os.sep + 'data/polygon-shape.csv', index=False, encoding='gbk')